package com.qw.wx.config;

import me.chanjar.weixin.common.bean.menu.WxMenu;
import me.chanjar.weixin.common.bean.menu.WxMenuButton;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpConfigStorage;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;

import static me.chanjar.weixin.common.api.WxConsts.MenuButtonType;

import java.util.ResourceBundle;

public class MenuConfig {

  /**
   * 定义菜单结构
   *
   * @return
   */
  protected static WxMenu getMenu(WxMpService wxMpService) {
    WxMenu menu = new WxMenu();
    
    WxMenuButton button1 = new WxMenuButton();
    button1.setType(MenuButtonType.VIEW);
    button1.setName("市政大厅");
    button1.setUrl(wxMpService.oauth2buildAuthorizationUrl("/qf/portal/index.html", "snsapi_base", ""));
    
    WxMenuButton button2 = new WxMenuButton();
    button2.setType(MenuButtonType.VIEW);
    button2.setName("微信矩阵");
    button2.setUrl(wxMpService.oauth2buildAuthorizationUrl("http://dcwz.gog.cn/player.html?id=925999713432371200&from=singlemessage", "snsapi_base", ""));

    menu.getButtons().add(button1);
    menu.getButtons().add(button2);

    return menu;
  }

  public static class MainConfig {

    private String appId;
    private String appSecret;
    private String token;
    private String aesKey;

    /**
     * 为了生成自定义菜单使用的构造函数
     *
     * @param appId
     * @param appSecret
     * @param token
     * @param aesKey
     */
    protected MainConfig(String appId, String appSecret, String token, String aesKey) {
      this.appId = appId;
      this.appSecret = appSecret;
      this.token = token;
      this.aesKey = aesKey;
    }

    public WxMpConfigStorage wxMpConfigStorage() {
      WxMpInMemoryConfigStorage configStorage = new WxMpInMemoryConfigStorage();
      configStorage.setAppId(this.appId);
      configStorage.setSecret(this.appSecret);
      configStorage.setToken(this.token);
      configStorage.setAesKey(this.aesKey);
      return configStorage;
    }

    public WxMpService wxMpService() {
      WxMpService wxMpService = new WxMpServiceImpl();
      wxMpService.setWxMpConfigStorage(wxMpConfigStorage());
      return wxMpService;
    }

  }

  /**
   * 运行此main函数即可生成公众号自定义菜单
   *
   * @param args
   */
  public static void main(String[] args) {
    ResourceBundle resource = ResourceBundle.getBundle("wx_config");
    
    MainConfig mainConfig = new MainConfig(
        resource.getString("appId"), 
        resource.getString("appSecret"), 
        resource.getString("token"), 
        resource.getString("aesKey"));
    WxMpService wxMpService = mainConfig.wxMpService();
    try {
      wxMpService.getMenuService().menuCreate(getMenu(wxMpService));
    } catch (WxErrorException e) {
      e.printStackTrace();
    }
  }

}
